package com.doupi.partner.op.controller.profit;

import com.doupi.partner.constant.PartnerTypeEnum;
import com.doupi.partner.constant.ProfitSourceEnum;
import com.doupi.partner.manager.ProfitManager;
import com.doupi.partner.model.PartnerRelation;
import com.doupi.partner.model.Profit;
import com.doupi.partner.op.util.ExcelUtil;
import com.doupi.partner.op.util.OpUtils;
import com.doupi.partner.service.ProfitService;
import com.doupi.partner.service.dto.AdministratorDto;
import com.doupi.partner.util.AssertUtils;
import com.doupi.partner.util.DataTableData;
import com.doupi.partner.util.Pagination;
import com.doupi.partner.util.constant.UtilConstants;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.ibatis.session.RowBounds;
import org.junit.Assert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 收益
 */
@Controller
@RequestMapping("profit/{type}")
public class ProfitController {
	private final static String TEMPLATE_FOLDER = "profit/";

	private final ProfitService profitService;

	private final ProfitManager profitManager;

	@Autowired
	public ProfitController(ProfitService profitService, ProfitManager profitManager) {
		this.profitService = profitService;
		this.profitManager = profitManager;
	}

	@RequestMapping(value = "index", method = RequestMethod.GET)
	public String index(ModelMap modelMap, @PathVariable("type") Byte type) {
		modelMap.put("type", type);
		return TEMPLATE_FOLDER + "index";
	}

	@ResponseBody
	@RequestMapping(value = "list", method = RequestMethod.POST)
	public DataTableData<Profit> list(@PathVariable("type") Byte type, Integer offset, Integer limit, Profit profit) throws ParseException {
		AdministratorDto administratorDto = OpUtils.getCurrentLoginAdministrator();
		ProfitSourceEnum profitSource = ProfitSourceEnum.getProfitSourceByCode(type);
		AssertUtils.assertNotNull(profitSource, "收益类型不存在");
		profit.setType(profitSource.getCode());
		profit.setStatus(UtilConstants.YES); // 有效的收益

		if (administratorDto.isPartner()) { // 合伙人
			PartnerRelation partnerRelation = administratorDto.getPartnerRelation();
			PartnerTypeEnum partnerType = PartnerTypeEnum.getPartnerTypeByCode(partnerRelation.getType());
			Assert.assertNotNull(partnerType);
			switch (partnerType) {
			case HEADQUARTERS:
				break;
			case SUBSTATION:
				profit.setAdministratorId(partnerRelation.getAdministratorId());
				profit.setSuperiorPartnerAdministratorId(partnerRelation.getAdministratorId());
				profit.setCityAdministratorId(partnerRelation.getAdministratorId());
				profit.setSubstationAdministratorId(partnerRelation.getAdministratorId());
				break;
			case CITY:
				profit.setAdministratorId(partnerRelation.getAdministratorId());
				profit.setSuperiorPartnerAdministratorId(partnerRelation.getAdministratorId());
				profit.setCityAdministratorId(partnerRelation.getAdministratorId());
				break;
			case SUPERIOR:
				profit.setAdministratorId(partnerRelation.getAdministratorId());
				profit.setSuperiorPartnerAdministratorId(partnerRelation.getAdministratorId());
				break;
			case SECOND:
				profit.setAdministratorId(partnerRelation.getAdministratorId());
				break;
			default:
				break;
			}
		}
		if (administratorDto.isBusiness()) {
			profit.setBusinessAdministratorId(administratorDto.getId());
		}

		profit.setAdministratorId(administratorDto.getPartnerRelation().getAdministratorId());
		Pagination<Profit, Profit> pagination = new Pagination<>(offset, limit, profit);
		pagination = profitService.queryProfitWithAnnotation(pagination);
		return new DataTableData<>(pagination.getTotalCount(), profitManager.convertProfitListToDtoList(pagination.getRecords()));
	}

	@RequestMapping(value = "excel", method = RequestMethod.GET)
	public void excel(HttpServletRequest request, HttpServletResponse response, @PathVariable("type") Byte type, Profit profit) throws ParseException, IOException {
		response.setContentType("application/msexcel;");
		response.setHeader("Content-Disposition", "attachment;filename=sheet.xls");

		AdministratorDto administratorDto = OpUtils.getCurrentLoginAdministrator();
		ProfitSourceEnum profitSource = ProfitSourceEnum.getProfitSourceByCode(type);
		AssertUtils.assertNotNull(profitSource, "收益类型不存在");
		profit.setType(profitSource.getCode());
		profit.setStatus(UtilConstants.YES); // 有效的收益
		profit.setAdministratorId(administratorDto.getPartnerRelation().getAdministratorId());
		List<Profit> profitList = profitService.queryProfitWithAnnotation(profit, new RowBounds());

		List<Map<String, Object>> list = createExcelRecord(profitList);
		String columnNames[] = { "收益", "创建时间" };// 列名
		String keys[] = { "realAmount", "createTime" };// map中的key
		ExcelUtil.createWorkBook(list, keys, columnNames).write(response.getOutputStream());
	}

	// TODO 手动添加用户，权限比较重要，只能具有权限的人员操作，敏感, 年费的录入
	@RequestMapping(value = "edit", method = RequestMethod.GET)
	public String edit() {
		return TEMPLATE_FOLDER + "edit";
	}

	// TODO 手动添加用户，权限比较重要，只能具有权限的人员操作，敏感
	@RequestMapping(value = "save", method = RequestMethod.POST)
	public String save(Profit profit) {
		profit.setStatus(Byte.valueOf("0"));
		profitService.insert(profit);
		return "redirect:index";
	}

	private List<Map<String, Object>> createExcelRecord(List<Profit> profits) {
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("sheetName", "sheet1");
		list.add(map);
		Profit profit;
		for (int j = 0; j < profits.size(); j++) {
			profit = profits.get(j);
			Map<String, Object> mapValue = new HashMap<>();
			mapValue.put("realAmount", profit.getRealAmount());
			mapValue.put("createTime", DateFormatUtils.format(profit.getCreateTime(), UtilConstants.YYYY_MM_DD_HH_MM_SS));
			list.add(mapValue);
		}
		return list;
	}
}
